/*
 * @lc app=leetcode.cn id=725 lang=javascript
 *
 * [725] 分隔链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} root
 * @param {number} k
 * @return {ListNode[]}
 */
var splitListToParts = function (root, k) {
  // 计算链表长度
  const getLinkedSize = (head) => {
    let size = 0;
    let temp = head;
    while (temp) {
      temp = temp.next;
      size++;
    }
    return size;
  };

  let result = new Array(k);
  let size = getLinkedSize(root);
  // 每组的节点数
  let items = (size / k) >> 0;
  // 余数节点
  let remainder = size % k;
  // 记录余数使用数量
  let m = 0;
  // 虚拟头节点
  const dummy = new ListNode(-1);
  dummy.next = root;
  let prev = dummy;
  //
  for (let i = 0; i < k; i++) {
    let curr = prev;
    // 计算每组几个节点
    let j = 0;
    while (j++ < items) {
      curr = curr ? curr.next : null;
    }
    // 余数的节点分给前面的组
    if (m++ < remainder) {
      curr = curr ? curr.next : null;
    }
    // 存入结果
    result[i] = prev.next;
    // 头指针后移
    prev.next = curr.next;
    // 将链表断开
    if (curr) curr.next = null;
  }

  return result;
};
// @lc code=end
